package com.htx.zqs.blesmartmask.ui.fragment;

import android.support.annotation.NonNull;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.View;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.google.gson.Gson;
import com.htx.zqs.blesmartmask.R;
import com.htx.zqs.blesmartmask.bean.BeforeCourseData;
import com.htx.zqs.blesmartmask.bean.Contants;
import com.htx.zqs.blesmartmask.bean.ThirdInfoBean;
import com.htx.zqs.blesmartmask.listeners.OkListener;
import com.htx.zqs.blesmartmask.ui.activity.ChartActivity;
import com.htx.zqs.blesmartmask.ui.base.BaseFragment;
import com.htx.zqs.blesmartmask.ui.fragment.adapter.ThirdAdapter;
import com.htx.zqs.blesmartmask.utils.BlEUtile;
import com.htx.zqs.blesmartmask.utils.LocationUtil;
import com.htx.zqs.blesmartmask.utils.OkhttpUtils;
import com.htx.zqs.blesmartmask.utils.SPUtil;
import com.htx.zqs.blesmartmask.utils.Utils;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;

import butterknife.InjectView;

/**
 * Created by zhao on 2018/7/11.
 */

public class ThirdFragment extends BaseFragment implements OnRefreshListener {
    private static final String FATWB = "selectpageojtwo.link";
    @InjectView(R.id.recycle_view)
    RecyclerView recycleView;
    @InjectView(R.id.refreshLayout)
    SmartRefreshLayout refreshLayout;
    private OkhttpUtils mOkhttpUtils;
    private ThirdAdapter mAdapter;

    @Override
    protected int getLayoutId() {
        return R.layout.fragment_third;
    }

    @Override
    public void init() {
        mAdapter = new ThirdAdapter(getActivity());
        deviceid = LocationUtil.getUniquePsuedoID();
        initRecyclerView();
        initData();
    }

    private void initData() {
        if (BlEUtile.isNetworkConnected(getContext())) {
            type = true;
            postUserInfo(deviceid, 0);
        } else {
            showDb();
        }
    }

    private void initRecyclerView() {
        refreshLayout.setEnableRefresh(true);
        refreshLayout.setEnableLoadMore(false);
        refreshLayout.setOnRefreshListener(this);
        recycleView.setLayoutManager(new LinearLayoutManager(activity));
        mAdapter = new ThirdAdapter(activity);
        recycleView.setAdapter(mAdapter);
        mAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                ChartActivity.startAct(activity, courseNameList.get(position),
                        courseDateList.get(position), position == 0 ? 0 : 1);
            }
        });
    }

    @Override
    public void onRefresh(@NonNull RefreshLayout refreshLayout) {
        initData();
    }

    private void showDb() {
        courseDateList.clear();
        courseNameList.clear();
        List<ThirdInfoBean.DataBean.UserInfoBean> userInfoBeanList = new ArrayList<>();
        List<BeforeCourseData> beforeCourseDatas = BeforeCourseData.findAll();
        for (int i = 0; i < beforeCourseDatas.size(); i++) {
            BeforeCourseData beforeCourseData = beforeCourseDatas.get(i);
            String coursedate = beforeCourseData.getCoursedate();

            String name =Utils.getCourseNameInternal(getContext(),coursedate) ;
            if (!courseDateList.contains(coursedate)) {
                courseDateList.add(coursedate);
                courseNameList.add(name);
                ThirdInfoBean.DataBean.UserInfoBean userInfoBean = new ThirdInfoBean.DataBean.UserInfoBean();
                userInfoBean.setCoursedate(coursedate);
                userInfoBean.setName(name);
                userInfoBean.setId(Integer.parseInt(beforeCourseData.getSId()+""));
                userInfoBeanList.add(userInfoBean);
            }
            if (courseDateList.size() >= 10) {
                break;
            }
        }
//        Collections.sort(userInfoBeanList);
        mAdapter.setNewData(userInfoBeanList);
        refreshLayout.finishRefresh();
    }


    private ArrayList<String> courseNameList = new ArrayList();
    private ArrayList<String> courseDateList = new ArrayList();
    private String deviceid;
    private boolean type = true;
    private OkListener mListener = new OkListener() {
        @Override
        public void onSuccess(int requestCode, String string) {
            showThirdFgRc(string);
        }

        @Override
        public void onError(int requestCode, IOException e) {
        }
    };

    private void showThirdFgRc(String string) {
        if (TextUtils.isEmpty(string)) {
            return;
        }
        Gson gson = new Gson();
        ThirdInfoBean thirdInfoBean = gson.fromJson(string, ThirdInfoBean.class);
        ThirdInfoBean.DataBean data = thirdInfoBean.getData();
        List<ThirdInfoBean.DataBean.UserInfoBean> userInfoBeanList = data.getUserInfo();
        if (type) {
            courseDateList.clear();
            courseNameList.clear();
            SPUtil.put(getContext(), "ThirdInfoBean", string, "ThirdInfoBean");
        }

        for (ThirdInfoBean.DataBean.UserInfoBean userInfo : userInfoBeanList) {
            String courseName = userInfo.getName(getContext());
            String courseDate = userInfo.getCoursedate();
            courseNameList.add(courseName);
            courseDateList.add(courseDate);
        }
//        Collections.sort(userInfoBeanList);
        mAdapter.setNewData(userInfoBeanList);
        refreshLayout.finishRefresh();
    }

    private HashMap map = new HashMap();

    private void postUserInfo(String uuid, int index) {
        if (mOkhttpUtils == null) {
            mOkhttpUtils = new OkhttpUtils(getActivity(), Contants.GET_USER_INFO, mListener);
        }
        map.clear();
        map.put("deviceid", uuid);
        map.put("num", index);
        map.put("islogo", "A");
        mOkhttpUtils.postForm(Contants.GET_USER_INFO, Contants.BASE_URL + FATWB, map);
    }


    @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);
        boolean isNeedNetData = (boolean) SPUtil.get(getContext(), "isNeedNetData", false, "isNeedNetData");
        if (isNeedNetData) {
            initData();
        }
        isNeedNetData = false;
        SPUtil.put(getContext(), "isNeedNetData", isNeedNetData, "isNeedNetData");
    }


}
